import 'dart:io';

import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as p;

/// 图片压缩参数
class CompressImagesOptions {
  List<File> files;

  /// 大于多少 才压缩 单位MB
  double beginSize;

  /// 压缩质量 0-100之间
  int quality;

  /// 表示压缩后的宽度
  int minWidth;

  /// 表示压缩后的高度 如果原图小于minWidth或minHeight 则使用原图尺寸
  int minHeight;

  /// 是否纠正倒立的图
  bool autoCorrectionAngle;

  /// 压缩后的格式
  CompressFormat format;

  CompressImagesOptions(
    this.files, {
    this.beginSize = 0.5,
    this.quality = 90,
    this.minWidth = 1080,
    this.minHeight = 1080,
    this.autoCorrectionAngle = true,
    this.format = CompressFormat.jpeg,
  });
}

/// 压缩工具类
class CompressUtil {
  // 初始化一个单例实例
  static final CompressUtil _instance = CompressUtil._internal();

  factory CompressUtil() => _instance;

  CompressUtil._internal();

  /// 临时目录
  Directory? _dir;

  ///
  /// 压缩图片
  ///
  Future<List<File>> compressImages(CompressImagesOptions options) async {
    // 获取临时目录
    _dir ??= await getTemporaryDirectory();

    List<File> compressedFiles = [];

    for (var file in options.files) {
      // 获取文件大小（MB）
      int fileBytes = await file.length();
      var fileSize = Util.bytesToMegabytes(fileBytes);
      // 小于压缩大小 则跳过压缩
      if (fileSize < options.beginSize) {
        compressedFiles.add(file);
        continue;
      }
      // 生成压缩后的文件路径
      var targetPath =
          p.join(_dir!.absolute.path, '${Util.generateRandomString()}.jpeg');

      var result = await FlutterImageCompress.compressAndGetFile(
        file.absolute.path,
        targetPath,
        quality: getDynamicQuality(
          options.quality,
          options.beginSize,
          fileSize,
        ),
        minWidth: options.minWidth,
        minHeight: options.minHeight,
        autoCorrectionAngle: options.autoCorrectionAngle,
        format: options.format,
      );
      if (result != null) {
        compressedFiles.add(File(result.path));
      }
    }
    return compressedFiles;
  }

  /// 动态调整压缩质量
  /// 文件越大，压缩质量越低，但不低于 50
  int getDynamicQuality(int quality, double beginSize, double fileSize) {
    return (quality - (fileSize - beginSize) * 8).clamp(50, 100).toInt();
  }
}
